﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;

namespace Common
{
    public static class ImportExecl
    {

        public static Microsoft.Office.Interop.Excel.Application excel = null;
        public static  int rowIndex = 1;
        public static bool DataSetToExcel(DataTable dataTable, bool isShowExcle)
        {

            int rowNumber = dataTable.Rows.Count;

        
            int colIndex = 0;


            if (rowNumber == 0)
            {
                return false;
            }
            if (excel != null)
            {

                excel.Quit();

                //int pid;

                //GetWindowThreadProcessId(new IntPtr(excel.Hwnd), out pid);

                //System.Diagnostics.Process.GetProcessById(pid).Kill();
                excel = null;
            }
            //建立Excel对象
            if (excel == null)
            {
                rowIndex = 1;
                excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Application.Workbooks.Add(true);
                excel.Visible = isShowExcle;

                //生成字段名称
                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;
                    excel.Cells[1, colIndex] = col.ColumnName;
                }

            }
            else
            {
                rowIndex = excel.Rows.Count;
            }
            //填充数据
            foreach (DataRow row in dataTable.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;
                    excel.Cells[rowIndex, colIndex] = row[col.ColumnName];
                }
            }

            return true;
        }




    }
}
